﻿using System;
using System.Data.SQLite;
using System.Security.Cryptography;
using System.Text;

namespace PlaneBombGame
{
    internal class UserManager
    {
        private static readonly string DatabaseFilePath = "users.db";

        static UserManager()
        {
            InitializeDatabase();
        }

        private static void InitializeDatabase()
        {
            if (!System.IO.File.Exists(DatabaseFilePath))
            {
                SQLiteConnection.CreateFile(DatabaseFilePath);
                using (var connection = new SQLiteConnection($"Data Source={DatabaseFilePath};Version=3;"))
                {
                    connection.Open();
                    string sql = "CREATE TABLE Users (Username TEXT PRIMARY KEY, PasswordHash TEXT)";
                    using (var command = new SQLiteCommand(sql, connection))
                    {
                        command.ExecuteNonQuery();
                    }
                }
            }
        }

        public static bool Register(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                return false; // 用户名或密码不能为空
            }

            if (username.Contains(" ") || password.Contains(" "))
            {
                return false; // 用户名或密码中不能包含空格
            }

            string hashedPassword = HashPassword(password);
            using (var connection = new SQLiteConnection($"Data Source={DatabaseFilePath};Version=3;"))
            {
                connection.Open();
                string sql = "INSERT INTO Users (Username, PasswordHash) VALUES (@Username, @PasswordHash)";
                using (var command = new SQLiteCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@Username", username);
                    command.Parameters.AddWithValue("@PasswordHash", hashedPassword);
                    try
                    {
                        command.ExecuteNonQuery();
                        return true;
                    }
                    catch
                    {
                        return false; // 用户名已存在
                    }
                }
            }
        }

        public static bool Login(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                return false; // 用户名或密码不能为空
            }

            if (username.Contains(" ") || password.Contains(" "))
            {
                return false; // 用户名或密码中不能包含空格
            }

            using (var connection = new SQLiteConnection($"Data Source={DatabaseFilePath};Version=3;"))
            {
                connection.Open();
                string sql = "SELECT PasswordHash FROM Users WHERE Username = @Username";
                using (var command = new SQLiteCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@Username", username);
                    var reader = command.ExecuteReader();
                    if (reader.Read())
                    {
                        string storedHash = reader.GetString(0);
                        return VerifyPassword(password, storedHash);
                    }
                }
            }
            return false; // 用户名不存在
        }

        private static string HashPassword(string password)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(password);
                byte[] hash = sha256.ComputeHash(bytes);
                return BitConverter.ToString(hash).Replace("-", "").ToLower();
            }
        }

        private static bool VerifyPassword(string password, string hashedPassword)
        {
            string hashOfInput = HashPassword(password);
            return hashOfInput == hashedPassword;
        }
    }
}